package com.ruoyi.api.controller.user;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruoyi.api.controller.common.AbstractApiController;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.redis.RedisUtils;
import com.ruoyi.framework.web.service.ApiTokenService;
import com.ruoyi.user.domain.User;
import com.ruoyi.user.domain.dto.RegisterOrLoginDTO;
import com.ruoyi.user.domain.vo.AuthorizationVO;
import com.ruoyi.user.domain.vo.UserVo;
import com.ruoyi.user.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * 小程序用户管理Controller
 *
 * @author wuchao
 * @date 2022-03-03
 */
@Validated
@Api(value = "小程序用户管理控制器", tags = {"小程序用户管理管理"})
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/miniapp/user")
@Slf4j
public class ApiUserLoginController extends AbstractApiController {

    @Autowired
    private IUserService userService;

    @Autowired
    private ApiTokenService apiTokenService;

    @Value("${api-token.expireTime}")
    private int expireTime;


    /**
     * 获取手机用户手机号
     */
    @ApiOperation("登录注册")
    @PostMapping("/register-or-login")
    public R<String> registerOrLogin(@RequestBody @Validated RegisterOrLoginDTO dto) {
        User user = userService.registerOrLogin(dto.getCode(), dto.getOpenId(), dto.getUnionId());
        String token = apiTokenService.generateToken(user);
        RedisUtils.setCacheObject(Constants.APP_ONLINE_TOKEN_KEY + token, user, expireTime, TimeUnit.SECONDS);
        return R.ok("success", token);
    }

    /**
     * 小程序授权
     *
     * @return
     */
    @ApiOperation("小程序koc用户授权")
    @GetMapping("/authorization")
    public R<AuthorizationVO> kocAuthorization(String code) {
        AuthorizationVO authorization = userService.authorization(code);
        if (ObjectUtils.isNotEmpty(authorization.getUserId())) {
            UserVo userVo = userService.queryById(authorization.getUserId());
            User user = BeanUtil.toBean(userVo, User.class);
            String token = apiTokenService.generateToken(user);
            authorization.setToken(token);
            RedisUtils.setCacheObject(Constants.APP_ONLINE_TOKEN_KEY + token, user, expireTime, TimeUnit.SECONDS);
        }
        return R.ok(authorization);
    }

    /**
     * 登录检查
     *
     * @return
     */
    @ApiOperation("登录检查")
    @GetMapping("/check")
    public R<User> check(String openId) {
        return R.ok(userService.check(openId));
    }

}
